import md5 from "blueimp-md5";
const secret = '52f4133a5d45'; //得到url签名

function getSign(params) {
  var timestamp = new Date().getTime();
  var times = timestamp.toString(); //一定要转换字符串

  params.resttime = Math.floor(Number(times) / 1000);
  params = valuesSort(params);
  params = switchUpper(params); //对所有需要传入的参数加上appkey作一次key＝value字典序的排序

  var keyvaluestring = params + '&' + secret; // console.log(keyvaluestring);
  // alert(keyvaluestring);
  //对排序后的参数进行MD5加密

  var sign = md5(keyvaluestring).toString();
  return sign;
} //对值进行排序


function valuesSort(params) {
  var keys = [],
      name;

  for (name in params) {
    if (params.hasOwnProperty(name)) {
      keys.push(name);
    }
  }

  keys = keys.sort();
  var no = {};

  for (var i = 0; i < keys.length; i++) {
    no[keys[i]] = params[keys[i]];
  }

  return no;
}

function switchUpper(params) {
  var str = '';

  for (var t in params) {
    if (typeof params[t] === 'string' || typeof params[t] === 'number' || typeof params[t] === 'boolean') {
      str += urlencode(t) + '=' + urlencode(params[t]) + '&';
    } else if (params[t] !== null && typeof params[t] === 'object') {
      str += switchUpperObject(params[t], t) + '&';
    }
  }

  return str.substring(0, str.lastIndexOf('&'));
}

function switchUpperObject(params, name) {
  var str = '';
  params = valuesSort(params);

  for (var t in params) {
    if (typeof params[t] === 'string' || typeof params[t] === 'number' || typeof params[t] === 'boolean') {
      str += urlencode(name + '[' + t + ']') + '=' + urlencode(params[t]) + '&';
    } else if (typeof params[t] === 'object') {
      str += switchUpperObject(params[t], name + '[' + t + ']') + '&';
    }
  }

  str = str.substring(0, str.lastIndexOf('&'));
  return str;
} //url特殊字符替换


function urlencode(str) {
  str = encodeURIComponent(str);
  str = str.replace(/\!/g, "%21");
  str = str.replace(/\*/g, "%2A");
  str = str.replace(/\(/g, "%28");
  str = str.replace(/\)/g, "%29");
  str = str.replace(/\'/g, "%27");
  str = str.replace(/\~/g, "%7E");
  return str.replace(/%20/g, '+');
}

module.exports = {
  getSign: getSign
};